﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Evolution.UI.WebParts
{
    [Serializable]
    public class PageAssertion : BaseAssertion
    {
        #region Properties

        public override string Caption
        {
            get { return "Page"; }
        }

        public PostBackStatusOperator Operator { get; set; }

        #endregion

        #region Methods

        public override void CreateInterface(ControlCollectionBuilder builder, PageActionEditor editor, int index)
        {
            DropDownList pagePostBackStatus = new DropDownList();
            pagePostBackStatus.ID = "PageOperator" + index;
            pagePostBackStatus.Width = Unit.Pixel(150);
            pagePostBackStatus.Items.Add(new ListItem("is post back", PostBackStatusOperator.IsPostBack.ToString()));
            pagePostBackStatus.Items.Add(new ListItem("is not post back", PostBackStatusOperator.IsNotPostBack.ToString()));

            builder.AddControl(pagePostBackStatus);
        }

        public override string GetDescription()
        {
            return String.Format("Page {0}", this.Operator == PostBackStatusOperator.IsPostBack ? "is post back" : "is not post back");
        }

        public override void SyncChanges(PageActionEditor editor, int index)
        {
            (editor.FindControl("PageOperator" + index) as DropDownList).SelectedValue = this.Operator.ToString();
        }

        public override void ApplyChanges(PageActionEditor editor, int index)
        {
            this.Operator = (PostBackStatusOperator)Enum.Parse(typeof(PostBackStatusOperator), (editor.FindControl("PageOperator" + index) as DropDownList).SelectedValue);
        }

        public override bool Evaluate(Page page, PageActionWebPart part)
        {
            return page.IsPostBack && this.Operator == PostBackStatusOperator.IsPostBack || !page.IsPostBack && this.Operator == PostBackStatusOperator.IsNotPostBack; 
        }

        #endregion
    }

    #region PostBackStatusOperator enum

    public enum PostBackStatusOperator
    {
        IsPostBack = 0,
        IsNotPostBack = 1
    }

    #endregion
}
